package com.southgis.nr.fileUpload.controller;

import jdk.nashorn.internal.objects.annotations.Getter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;


/**
 * @author Admin
 */
@Controller
public class FileController {


    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "C://temp//";

    /**
     * 获取上传文件界面
     *
     * @return
     */
    @GetMapping("")
    public String goUploadPage() {
        return "uploader";
    }

    /**
     * 单文件上传
     *
     * @param file
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/upload")
    public String uploadSingleFile(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择一个文件进行上传");
            return "redirect:uploadStatus";
        }

        // Get the file and save it somewhere
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message",
                    "上传成功：" + file.getOriginalFilename());

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }


    @RequestMapping("/demo")
    @ResponseBody
    public String getHello() {
        return "demo";
    }

}
